package weathercrowd.utilities;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpSession;

import weathercrowd.managers.*;
import weathercrowd.utilities.*;

public class SessionHelper {
	/**
	 * 
	 * @param session the entity manager to return should be tied to
	 * @return entity manager that has been tied to or newly created and made tied to the session
	 */
	public static EntityManager getEntityManager(HttpSession session) {
		Object oEm = session.getAttribute(SessionAttributes.EntityManager);
		EntityManager em;
		if (oEm == null) {
			EntityManagerFactory emf = PersistenceHelper.get();
			em = emf.createEntityManager();
			session.setAttribute(SessionAttributes.EntityManager, em);
		} else {
			em = (EntityManager)oEm;
		}
		return em;
	}
	
	/**
	 * closes the entity manager in the session and sets the attribute to null if any 
	 * @param session the session to which the entity manager is tied
	 */
	public static void closeEntityManager(HttpSession session) {
		Object oEm = session.getAttribute(SessionAttributes.EntityManager);
		if (oEm == null) {
			return;
		}
		EntityManager em = (EntityManager)oEm;
		session.setAttribute(SessionAttributes.EntityManager, null);
		em.close();
	}
	
	public static PersistenceManager getPersistenceManager(HttpSession session) {
		Object oPm = session.getAttribute(SessionAttributes.PersistenceManager);
		if (oPm != null) {
			return (PersistenceManager)oPm;
		}
		
		EntityManager em = getEntityManager(session);
		
		PersistenceManager pm = new PersistenceManager(em);
		session.setAttribute(SessionAttributes.PersistenceManager, pm);
		
		return pm;
	}
}
